<template>
  <div class="page-container">
    <!-- 头部导航 -->
    <header class="header">
      <BackBtn />
      <h1>提案最终批复管理</h1>
      <Time />
    </header>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 搜索和筛选区域 -->
      <div class="search-section">
        <el-input 
          v-model="searchText" 
          placeholder="支持搜索案由、提案人、提案号" 
          class="search-input"
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button 
              type="button" 
              class="search-btn"
              @click="handleSearch"
            >
              <el-icon class="search-icon">
                <Search />
              </el-icon>
            </el-button>
          </template>
        </el-input>

        <div class="filter-section">
          <!-- 日期范围选择 -->
          <div class="date-range-picker">
            <el-date-picker 
              v-model="dateRange[0]" 
              type="date" 
              placeholder="开始日期" 
              class="date-picker"
              @change="handleFilterChange" 
            />
            <span class="separator">—</span>
            <el-date-picker 
              v-model="dateRange[1]" 
              type="date" 
              placeholder="结束日期" 
              class="date-picker"
              @change="handleFilterChange" 
            />
          </div>

          <!-- 时间选择 -->
          <el-select v-model="sortBy" placeholder="排序：提案时间(倒序)" @change="handleFilterChange">
            <el-option label="提案时间(倒序)" value="desc" />
            <el-option label="提案时间(正序)" value="asc" />
          </el-select>

          <!-- 类型筛选 -->
          <div class="advanced-filters">
            <el-select v-model="proposalType" @change="handleFilterChange" placeholder="提案类型：全部">
              <el-option label="类型筛选：全部" value="all" />
              <el-option label="医疗健康类" value="医疗健康类" />
              <el-option label="教育科技类" value="教育科技类" />
              <el-option label="文化体育类" value="文化体育类" />
              <el-option label="城市建设类" value="城市建设类" />
              <el-option label="环境保护类" value="环境保护类" />
              <el-option label="社会治理类" value="社会治理类" />
              <el-option label="经济发展类" value="经济发展类" />
              <el-option label="其他类" value="其他类" />
            </el-select>
          </div>

          <!-- 状态筛选 -->
          <el-select v-model="status" @change="handleFilterChange" placeholder="状态筛选：全部">
            <el-option label="状态筛选：全部" value="all" />
            <el-option label="已通过" value="处理完结" />
            <el-option label="已驳回" value="已驳回" />
          </el-select>

          <!-- 导出按钮 -->
          <el-button type="danger"  style="margin-left: auto" @click="handleExport">导 出</el-button>
        </div>
      </div>

      <!-- 表格区域 -->
      <div class="table-section" v-loading="loading" element-loading-text="加载中..." element-loading-background="rgba(255, 255, 255, 0.8)">
        <div class="news-list">
          <!-- 添加表头 -->
          <div class="news-header">
            <div class="header-item">案由</div>
            <div class="header-item">提案类型</div>
            <div class="header-item" >提案人</div>
            <div class="header-item"  style="margin-left: 65px;">专项处理结束时间</div>
            <div class="header-item" >操作</div>
          </div>
          <!-- 无数据显示 -->
          <div v-if="!tableData || tableData.length === 0" class="no-data">
            <el-empty description="暂无数据" />
          </div>
          <!-- 数据列表 -->
          <div v-else v-for="(item, index) in tableData" :key="index" class="news-item">
            <div class="line"></div>
            <div class="news-info" @click="handleRowClick(item)">
              <div class="info-value" style="flex: 2">
                {{ item.caseReason }}
                <span v-if="item.isCancel" class="cancel-tag">申请取消</span>
              </div>
              <div class="info-value">{{ item.proposalType }}</div>
              <div class="info-value" style="margin-left: 30px;">{{ item.proposer }}</div>
              <div class="info-value" style="margin-left: 60px;">{{ formatDate(item.specialHandlingTime) }}</div>
            </div>
            <div class="news-actions">
              <!-- 驳回按钮 -->
              <el-button
                v-if="['专项处理'].includes(item.status)"
                type="danger"
                @click="handleReject(item)"
              >
                驳回
              </el-button>
              <el-button
                v-if="item.status === '已驳回'"
                type="danger"
                disabled
              >
                已驳回
              </el-button>

              <!-- 退回按钮 -->
              <el-button
                v-if="['专项处理'].includes(item.status)"
                type="warning"
                @click="handleBack(item)"
              >
                退回
              </el-button>
              <el-button
                v-if="item.status === '已退回'"
                type="warning"
                disabled
              >
                已退回
              </el-button>
              
              <!-- 通过按钮 -->
              <el-button
                v-if="['专项处理'].includes(item.status)"
                type="primary"
                @click="handleApprove(item)"
              >
                通过
              </el-button>
              <el-button
                v-if="['处理完结','最终批复'].includes(item.status)"
                type="primary"
                disabled
              >
                已通过
              </el-button>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div class="pagination-section">
          <el-pagination
            v-model:current-page="pageNum"
            v-model:page-size="pageSize"
            :page-sizes="[3, 5, 10, 15]"
            :background="false"
            layout="prev, pager, next, jumper"
            :total="total"
            @size-change="onSizeChange"
            @current-change="onCurrentChange"
          />
        </div>
      </div>
    </div>

    <!-- 添加自定义弹窗 -->
    <div v-if="showPublicDialog" class="custom-dialog-overlay">
      <div class="custom-dialog">
        <div class="dialog-content">
          <h3>是否公示</h3>
          <p>此提案是否被公示</p>
          <div class="radio-group">
            <label class="radio-label">
              <input 
                type="radio" 
                v-model="publicChoice" 
                :value="true"
                class="radio-input"
              >
              <span class="radio-text">是</span>
            </label>
            <label class="radio-label">
              <input 
                type="radio" 
                v-model="publicChoice" 
                :value="false"
                class="radio-input"
              >
              <span class="radio-text">否</span>
            </label>
          </div>
          <button class="confirm-btn" @click="handlePublicConfirm">确定</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted,h } from 'vue'
import { useRouter } from 'vue-router'
import { ArrowLeft, Search } from '@element-plus/icons-vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { updateProposalStatus, sendBack, updatePublicStatus, exportProposals } from '@/api/proposal.js'
import { useProposalStore } from '@/stores/proposal.js'
import { storeToRefs } from 'pinia'
import Time from '@/components/Time.vue'
import BackBtn from '@/components/Back-btn.vue'

// 使用 proposal store
const proposalStore = useProposalStore()

// 使用 store 中的状态
const { 
  tableData,
  total,
  pageNum,
  pageSize,
  dateRange,
  sortBy,
  status,
  searchText,
  proposalType
} = storeToRefs(proposalStore)

// 筛选
const router = useRouter()
const loading = ref(false)

// 重置所有筛选条件的函数
const resetFilters = () => {
  searchText.value = ''  // 重置搜索文本
  dateRange.value = [null, null]  // 重置日期范围
  sortBy.value = 'desc'  // 重置时间排序为默认的倒序
  proposalType.value = 'all'  // 重置提案类型为全部
  status.value = 'all'  // 重置状态筛选为全部
  pageNum.value = 1
}

// 在组件挂载时获取提案数据
onMounted(() => {
  resetFilters()  // 初始化重置
  loading.value = true
  proposalStore.fetchProposalData()
  loading.value = false
})

// 分页处理
const onSizeChange = (size) => {
  pageSize.value = size
  proposalStore.fetchProposalData()
}

const onCurrentChange = (num) => {
  pageNum.value = num
  proposalStore.fetchProposalData()
}

// 筛选条件变化时的处理
const handleFilterChange = () => {
  proposalStore.fetchProposalData()
}

// 添加退回提案的方法
const handleSendBack = async (proposalId) => {
  try {
    await sendBack({
      proposalId,
      status: '分流', 
      isOr: false,
      pageStatus: 4 // 最终批复页面的状态码
    })
    // 退回成功后刷新数据
    await proposalStore.fetchProposalData()
  } catch (error) {
    console.error('退回提案失败：', error)
    throw error
  }
}

// 处理驳回
const handleReject = async (row) => {
  // 弹出确认窗口
  const confirmResult = await ElMessageBox.confirm(
    `确定要驳回 ${row.proposer} 的提案吗？`,
    '确认操作',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).catch(() => {
    // 用户点击取消时，直接返回
    return false;
  });

  if (confirmResult) {
    try {
      // 更新状态时同时设置 isOr 为 false，pageStatus为3（分流页面）
      await updateProposalStatus({
        pid: row.pid,
        status: '已驳回',
        isOr: false,
        pageStatus: 4
      });
      ElMessage.success(`已驳回 ${row.proposer} 的提案`);
      row.status = '已驳回';
      row.isShunt = false; // 更新本地状态
      // 刷新数据
      proposalStore.fetchProposalData();
    } catch (error) {
      ElMessage.error('驳回提案失败');
    }
  }
};

// 修改退回按钮的处理函数
const handleBack = async (row) => {
  try {
    // 弹出确认窗口
    await ElMessageBox.confirm(
      `确定要退回 ${row.proposer} 的提案吗？`,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    // 调用退回方法
    await handleSendBack(row.pid)
    ElMessage.success(`已退回 ${row.proposer} 的提案`)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('退回失败:', error)
      ElMessage.error('退回提案失败')
    }
  }
}

// 添加控制弹窗显示的变量
const showPublicDialog = ref(false)
const publicChoice = ref(true)
const currentRow = ref(null)

// 关闭弹窗
const closePublicDialog = () => {
  showPublicDialog.value = false
  publicChoice.value = true
}

// 处理通过按钮点击
const handleApprove = async (row) => {
  try {
    // 第一个确认窗口 - 确认通过
    await ElMessageBox.confirm(
      `确定要通过 ${row.proposer} 的提案吗？`,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'success',
      }
    );

    // 更新状态为最终批复
    await updateProposalStatus({
      pid: row.pid,
      status: '最终批复',
      isOr: true,
      pageStatus: 4
    });

    // 显示公示选择弹窗
    currentRow.value = row
    showPublicDialog.value = true
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('操作失败:', error);
      ElMessage.error('操作失败');
    }
  }
}

// 处理公示确认
const handlePublicConfirm = async () => {
  try {
    // 更新公示状态
    await updatePublicStatus({
      pid: currentRow.value.pid,
      status: '处理完结',
      isOr: publicChoice.value,
      pageStatus: 4
    });

    ElMessage.success(`已完成 ${currentRow.value.proposer} 的提案处理`);
    currentRow.value.status = '处理完结';
    
    // 关闭弹窗
    closePublicDialog();
    
    // 刷新数据
    await proposalStore.fetchProposalData();
  } catch (error) {
    console.error('设置公示状态失败:', error);
    ElMessage.error('设置公示状态失败');
  }
}

// 处理搜索
const handleSearch = () => {
  proposalStore.fetchProposalData()
}

// 处理行点击
const handleRowClick = (row) => {
  router.push(`/proposal/detail/${row.pid}`)
}

// 添加日期格式化函数
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  return `${year}/${month}/${day} ${hours}:${minutes}`;
}

// 导出提案数据
const handleExport = async () => {
  try {
    loading.value = true
    
    // 格式化日期参数
    let startDate = null
    let endDate = null
    
    if (dateRange.value[0]) {
      const date = new Date(dateRange.value[0])
      startDate = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
    }
    
    if (dateRange.value[1]) {
      const date = new Date(dateRange.value[1])
      endDate = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
    }
    
    // 准备请求参数，与当前筛选条件保持一致
    const params = {
      pageStatus: 4, // 最终批复页面
      status: status.value !== 'all' ? status.value : null,
      proposalType: proposalType.value !== 'all' ? proposalType.value : null,
      startDate,
      endDate,
      searchText: searchText.value,
      sort: sortBy.value
    }
    
    // 调用导出API
    const response = await exportProposals(params)
    
    // 创建Blob对象
    const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    
    // 创建临时下载链接
    const link = document.createElement('a')
    link.href = URL.createObjectURL(blob)
    
    // 设置文件名
    const now = new Date()
    const timestamp = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}`
    link.download = `提案最终批复数据_${timestamp}.xlsx`
    
    // 模拟点击下载
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    
    ElMessage.success('导出提案数据成功')
  } catch (error) {
    console.error('导出提案数据失败:', error)
    ElMessage.error('导出提案数据失败')
  } finally {
    loading.value = false
  }
}

</script>

<style scoped>
@import '@/assets/css/proposal/list.css';
@import '@/assets/css/header/index.css';
@import '@/assets/css/others/pagination.css';
@import '@/assets/css/others/btn.css';
@import '@/assets/css/others/dateEditor.css';
@import '@/assets/css/others/search.css';
@import '@/assets/css/others/select.css';

/* 添加自定义弹窗样式 */
.custom-dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.no-data {
  padding: 40px 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #fff;
  border-radius: 4px;
  margin-top: 10px;
}

:deep(.el-empty__description) {
  margin-top: 10px;
  color: #909399;
}

.cancel-tag {
  display: inline-block;
  background-color: #f56c6c;
  color: white;
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 4px;
  margin-left: 8px;
  vertical-align: middle;
}

.custom-dialog {
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  width: 300px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.dialog-content {
  text-align: center;
}

.dialog-content h3 {
  margin: 0;
  padding: 10px 0;
  font-size: 18px;
  color: #333;
}

.dialog-content p {
  margin: 10px 0;
  color: #666;
  font-size: 14px;
}

.radio-group {
  margin: 20px 0;
  display: flex;
  justify-content: center;
  gap: 30px;
}

.radio-label {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.radio-input {
  width: 18px;
  height: 18px;
  margin-right: 8px;
  accent-color: #c8102e;
}

.radio-text {
  font-size: 16px;
  color: #333;
}

.confirm-btn {
  background-color: #c8102e;
  color: white;
  border: none;
  padding: 8px 40px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  margin-top: 10px;
}

.confirm-btn:hover {
  background-color: #a50d26;
}
</style>